package com.yangtzeu.jwc.business;

import java.io.File;
import java.io.FileNotFoundException;

import org.apache.http.Header;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.app.MyStorage;
import com.yangtzeu.jwc.customview.CustomeComfirmDialog;
import com.yangtzeu.jwc.customview.CustomeDownloadDialog;
import com.yangtzeu.jwc.customview.CustomeUpdateDialog;
import com.yangtzeu.jwc.domain.Version;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.DataUtil;
import com.zjsx.lib.utils.L;
import com.zjsx.lib.utils.T;

public class UpdateBusiness extends BaseBusiness implements OnClickListener, CheckVersionListener {
    CustomeUpdateDialog cud;
    CustomeDownloadDialog cdd;
    Version version;
    private String updateFileName = "长江大学教务处.apk";
    File downloadFile;
    AsyncHttpClient downloadClient;
    boolean downloadCancel = false;
    UpdateListener updateListener;

    public UpdateBusiness(Context context) {
        super(context);
        try {
            if(context.getExternalCacheDir() != null) {
                downloadFile = new File(context.getExternalCacheDir(), updateFileName);
            }else{
                downloadFile = new File(context.getCacheDir(), updateFileName);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public UpdateBusiness(Context context, UpdateListener updateListener) {
        this(context);
        this.updateListener = updateListener;
    }

    public void update(final CheckVersionListener listener) {
        checkUpdate(new CheckVersionListener() {
            @Override
            public void haveNewVersion(Version version) { // 有新版本
                if (listener != null)
                    listener.haveNewVersion(version);
                this.haveNewVersion(version);
            }

            @Override
            public void isViewVersion() { // 这就是最新版本
                if (listener != null)
                    listener.isViewVersion();
                this.isViewVersion();
            }

            @Override
            public void checkVersionFailed() {
                if (listener != null)
                    listener.checkVersionFailed();
                this.checkVersionFailed();
            }
        });
    }

    private void checkUpdate(final CheckVersionListener listener) {
        String url = G.APP_UPDATE;
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(10 * 1000);
        client.setMaxRetriesAndTimeout(0, 10 * 1000);
        client.post(url, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                listener.checkVersionFailed();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Log.d("检查更新成功", new String(responseBody));
                try {
                    onVersion(DataUtil.dataToObj(responseBody, Version.class));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void download(final FileAsyncHttpResponseHandler handler) {
        L.e("开始下载" + version.innerUrl);
        downloadClient = getNewClient();
        String downPath = version.innerUrl;
        if (version.innerUrl.startsWith("/")) {
            downPath = G.APP_SERVER_ROOT + version.innerUrl;
        }
        downloadClient.get(downPath, handler);
    }

    public void onVersion(Version version) {
        if (checkVersion(version)) {
            this.haveNewVersion(version);
        } else {
            this.isViewVersion();
        }
    }

    public boolean checkVersion(Version version) {
        return checkVersion(version.name);
    }

    public boolean checkVersion(String newestVersion) {
        String nowVersion = MyApplication.getInstance().getVersion(context);
        return checkVersion(nowVersion, newestVersion);
    }

    public static Boolean checkVersion(String nowVersion, String serVersion) {
        if ((null != serVersion) && (Integer.parseInt(nowVersion.replaceAll("\\.", "")) < Integer.parseInt(serVersion.replaceAll("\\.", "")))) {
            return true;
        }
        L.d(" getVersion  " + Integer.parseInt(nowVersion.replaceAll("\\.", "")) + " serVersion  " + Integer.parseInt(serVersion.replaceAll("\\.", "")));
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.update_cancel:
                if (cud != null && cud.isShowing()) {
                    cud.dismiss();
                }
                if (updateListener != null) {
                    updateListener.cancelUpdate();
                }
                break;
            case R.id.download_cancel:
                if (cdd != null && cdd.isShowing()) {
                    cdd.dismiss();
                }
                downloadCancel = true;
                if (updateListener != null) {
                    updateListener.cancelDownload();
                }
                break;
            case R.id.download_outer:
                downloadByExplorer();
                if (updateListener != null) {
                    updateListener.downloadFromExplorer();
                }
                break;
            case R.id.download_inner:
                if (cud != null && cud.isShowing()) {
                    cud.dismiss();
                }
                cdd = CustomeDownloadDialog.createDialog(context, this);
                cdd.setCancelable(false);
                cdd.show();
                if (downloadFile != null) {
                    download(new MDownloadListenner(downloadFile));
                } else {
                    download(new MDownloadListenner(context));
                }
                break;
            default:
                break;
        }
    }

    public void openExploereTips() {
        if (CustomeComfirmDialog.show(context, "网盘下载", "下载失败！是否尝试通过网盘下载？")) {
            downloadByExplorer();
            if (updateListener != null) {
                updateListener.downloadFromExplorer();
            }
        } else {
            if (updateListener != null) {
                updateListener.cancelDownloadFromExplorer();
            }
        }
    }

    public void downloadByExplorer() {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(version.outerUrl));
            context.startActivity(intent);
        } catch (Exception e) {
            T.showLong(context, "对不起,没有找到网盘地址！");
        }
    }

    class MDownloadListenner extends FileAsyncHttpResponseHandler {

        public MDownloadListenner(Context context) {
            super(context);
        }

        public MDownloadListenner(File file) {
            super(file);
        }

        @Override
        public void onProgress(int bytesWritten, int totalSize) {
            int progress = (bytesWritten * 100) / (totalSize);
            if (cdd != null) {
                cdd.setProgress(progress);
            }
            L.e("更新文件下载进度：" + progress);
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
            if (cdd != null && cdd.isShowing()) {
                cdd.dismiss();
            }
            openExploereTips();
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, File arg2) {
            if (!downloadCancel) {
                install();
            }
        }

    }

    public void install() {
        if (cdd != null && cdd.isShowing()) {
            cdd.dismiss();
        }
        if (downloadFile == null)
            return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 解决升级过程中闪退的问题
        intent.setDataAndType(Uri.fromFile(downloadFile), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    @Override
    public void haveNewVersion(Version version) {
        this.version = version;
        // TODO Auto-generated method stub
        cud = CustomeUpdateDialog.createDialog(context, "检测到新版本：" + version.name, UpdateBusiness.this);
        cud.setMsg(version.log);
        cud.setCancelable(false);
        cud.show();
    }

    @Override
    public void isViewVersion() {
        // TODO Auto-generated method stub
        Toast.makeText(context, "已经是最新版了！", Toast.LENGTH_LONG).show();
    }

    @Override
    public void checkVersionFailed() {
        // TODO Auto-generated method stub
        Toast.makeText(context, "检查更新失败！", Toast.LENGTH_LONG).show();
    }
}
